/*
 * Copyright (c) 2020 hebeiyiliuba.com
 * All rights reserved.
 *
 */
package org.jeecg.modules.third.daikai.fanyun.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.third.aliyunocr.utils.HttpUtils;
import org.jeecg.modules.third.daikai.fanyun.constant.FanyunConstant;
import org.jeecg.modules.third.daikai.fanyun.dto.FyApiBaseResDTO;
import org.jeecg.modules.third.daikai.fanyun.dto.contract.CarrierContractDTO;
import org.jeecg.modules.third.daikai.fanyun.dto.contract.CuoheContractDTO;
import org.jeecg.modules.third.daikai.fanyun.dto.driver.FyDriverDTO;
import org.jeecg.modules.third.daikai.fanyun.dto.finance.FySettlement;
import org.jeecg.modules.third.daikai.fanyun.dto.finance.FySettlementDTO;
import org.jeecg.modules.third.daikai.fanyun.dto.gps.FyGpsDTO;
import org.jeecg.modules.third.daikai.fanyun.dto.middleman.FyMiddlemanDTO;
import org.jeecg.modules.third.daikai.fanyun.dto.middleman.CarrierDTO;
import org.jeecg.modules.third.daikai.fanyun.dto.order.FyOrderDTO;
import org.jeecg.modules.third.daikai.fanyun.dto.order.OrdersDTO;
import org.jeecg.modules.third.daikai.fanyun.dto.payee.FyPayeeDTO;
import org.jeecg.modules.third.daikai.fanyun.dto.vehicle.FyVehicleDTO;
import org.jeecg.modules.wlhy.utils.HyCfgUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @BelongsPackage: org.jeecg.modules.third.daikai.fanyun.service
 * @Author: duanlikao
 * @CreateTime: 2023-02-07 09:16
 * @UpdateTime: 2023-08-11 09:16 for 重构
 * @Description: 梵运代开
 * @Version: 1.0
 */
@Service
@Slf4j
public class FanyunApiService {

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 获取Token
     *
     * @return
     */
    public String getToken() {
        if (!HyCfgUtil.isUsed("fanyun_daikai")){
            throw new JeecgBootException("梵运服务暂未开启,请联系管理员。");
        }

        Object tokenObj = redisUtil.hasKey(FanyunConstant.FANYUN_TOKEN_KEY) ?
                redisUtil.get(FanyunConstant.FANYUN_TOKEN_KEY) : null;
        //Object refreshTokenObj = redisUtil.hasKey(FanyunConstant.FANYUN_TOKEN_KEY) ?
        //        redisUtil.get(FanyunConstant.FANYUN_TOKEN_KEY) : null;
        if (ObjectUtil.isNotEmpty(tokenObj)) {
            return tokenObj.toString();
        }
//        else if (ObjectUtil.isEmpty(tokenObj) && ObjectUtil.isNotEmpty(refreshTokenObj)) {
//            //accessToken到期后建议使用refreshToken进行刷新，而不是使用用户名密码重新获取
//            return getRefreshtoken();
//        }

        //Map<String, String> headers = getHeaders();
        //Map<String, String> querys = new HashMap<>();
        // 拼装请求body的json字符串
        JSONObject requestObj = new JSONObject();
        requestObj.put("userName", HyCfgUtil.getCfgItem("fanyun_daikai","username"));
        requestObj.put("password", HyCfgUtil.getCfgItem("fanyun_daikai","password"));

        String domainuUrl = HyCfgUtil.getCfgItem("fanyun_daikai","url");
        String url = domainuUrl + FanyunConstant.FANYUN_GENERATE_TOKEN;
        String requestBody = requestObj.toString();
        log.info("梵运获取Token请求 -> {} ,{}", url, requestBody);
        try {
            String res = HttpUtil.post(url, requestBody);
            log.info("梵运获取Token回执 <- {} ", res);
            FyApiBaseResDTO result = JSONObject.parseObject(res , FyApiBaseResDTO.class);
            if (CommonConstant.SC_OK_200.intValue() == result.getCode()) {
                String dataString = StringUtils.isNotEmpty(result.getData().toString())
                        ? result.getData().toString() :  StringUtils.EMPTY;
                if (StringUtils.isNotEmpty(dataString)) {
                    JSONObject dataResult = JSONObject.parseObject(dataString);
                    String accessToken =  dataResult.getString("accessToken") ;
                    redisUtil.set(FanyunConstant.FANYUN_TOKEN_KEY, accessToken, FanyunConstant.FANYUN_TOKEN_KEY_EXPIRE);
                    redisUtil.set(FanyunConstant.FANYUN_REFRESHTOKEN_KEY, dataResult.getString("refreshToken"), FanyunConstant.FANYUN_REFRESHTOKEN_KEY_EXPIRE - 18000);
                    return accessToken;
                }
            } else {
                throw new JeecgBootException("验证权限失败,原因：" + result.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("梵运获取Token异常, {} ", e.getMessage());
        }

        return StringUtils.EMPTY;
    }


    /**
     * 刷新Token
     * @return
     */
    public String getRefreshtoken() {
        Object tokenObject  = redisUtil.hasKey(FanyunConstant.FANYUN_REFRESHTOKEN_KEY) ?
                redisUtil.get(FanyunConstant.FANYUN_REFRESHTOKEN_KEY) : null;
        if (tokenObject == null ) {
            return StringUtils.EMPTY;
        }

        String domainuUrl = HyCfgUtil.getCfgItem("fanyun_daikai","url");
        //String path = "/user/refresh_access_token";
        //Map<String, String> headers = getHeaders();
        //Map<String, String> querys = new HashMap<>();
        JSONObject requestObj = new JSONObject();
        requestObj.put("userName", HyCfgUtil.getCfgItem("fanyun_daikai","username"));
        requestObj.put("refreshToken", redisUtil.get(FanyunConstant.FANYUN_REFRESHTOKEN_KEY));

        String url = domainuUrl + FanyunConstant.FANYUN_REFRESH_TOKEN;
        String requestBody = requestObj.toString();
        log.info("梵运刷新Token请求 -> {} ,{}", url, requestBody);
        try {
            String res = HttpUtil.post(url, requestBody);
            log.info("梵运刷新Token回执 <- {} ", res);
            FyApiBaseResDTO result = JSONObject.parseObject(res, FyApiBaseResDTO.class);
            if (CommonConstant.SC_OK_200.intValue() == result.getCode()) {
                String dataString = StringUtils.isNotEmpty(result.getData().toString())
                        ? result.getData().toString() :  StringUtils.EMPTY;
                if (StringUtils.isNotEmpty(dataString)) {
                    JSONObject dataResult = JSONObject.parseObject(dataString);
                    String accessToken =  dataResult.getString("accessToken") ;
                    redisUtil.set(FanyunConstant.FANYUN_TOKEN_KEY, accessToken, FanyunConstant.FANYUN_TOKEN_KEY_EXPIRE - 18000);
                    redisUtil.set(FanyunConstant.FANYUN_REFRESHTOKEN_KEY, dataResult.getString("refreshToken"), FanyunConstant.FANYUN_REFRESHTOKEN_KEY_EXPIRE - 18000);
                    return accessToken;
                }
            }
        } catch (Exception e) {
            log.error("梵运刷新Token getRefreshtoken Exception :{} ", e.getMessage());
        }

        return StringUtils.EMPTY;
    }

    //业务接口认证公共头部
    private Map<String, String> getHeaders(){
        Map<String, String> headers = new HashMap<>();
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/json; charset=UTF-8");
        headers.put("User-Agent", "Mozilla/4.76");
        return headers;
    }

    /**
     * 经纪人
     * @param middlemanDTO
     * @return
     */
    public String middlemaPush(FyMiddlemanDTO middlemanDTO) {
        if(!HyCfgUtil.isUsed("fanyun_daikai")){
            throw new JeecgBootException("梵运服务暂未开启,请联系管理。");
        }
        if(middlemanDTO == null){
            throw new JeecgBootException("提交数据不能为空！");
        }
        String token = this.getToken();
        //判断token空
        if(StringUtils.isEmpty(token)) {
            throw new JeecgBootException("梵运服务Token为空！");
        }

        CarrierDTO carrierDTO = new CarrierDTO();
        carrierDTO.setMiddleman(middlemanDTO);
        carrierDTO.setOrganizationName(
                HyCfgUtil.getCfgItem("fanyun_daikai","fy_organizationName")
        );

        String requestBody = JSONObject.toJSONString(carrierDTO);
        String domainUrl = HyCfgUtil.getCfgItem("fanyun_daikai","url");

        String res = StrUtil.EMPTY;
        String url = domainUrl + FanyunConstant.FANYUN_OPEN_MIDDLEMAN_CREATE +
                "?access_token=" + token;
        try {
            log.info("梵运创建承运人（经纪人）接口请求 -> {}", url, requestBody);
            res = HttpUtil.post(url, requestBody);
            log.info("梵运创建承运人（经纪人）接口回执 <- {} ", res);
            FyApiBaseResDTO result = JSONObject.parseObject(res, FyApiBaseResDTO.class);
            if (CommonConstant.SC_OK_200.intValue() == result.getCode()) {
                return res;
            }

            if (401 == result.getCode()) {
                redisUtil.del(FanyunConstant.FANYUN_TOKEN_KEY);
                throw new JeecgBootException("认证过期,请重新推送数据。");
            }
        } catch (Exception e) {
            log.info("FanyunApiService middlemaPush  Exception :{} ",e.getMessage());
        }

        return res;
    }

    /**
     * 司机
     * @param fyDriverDTO
     * @return
     */
    public String driverPush(FyDriverDTO fyDriverDTO){

        if (!HyCfgUtil.isUsed("fanyun_daikai")) {
            throw new JeecgBootException("梵运服务暂未开启,请联系管理。");
        }
        if (fyDriverDTO == null) {
            throw new JeecgBootException("提交数据不能为空！");
        }
        String token = this.getToken();
        //判断token空
        if(StringUtils.isEmpty(token)) {
            throw new JeecgBootException("梵运服务Token为空！");
        }

        fyDriverDTO.setOrganizationName(
                HyCfgUtil.getCfgItem2("fanyun_daikai","fy_organizationName")
        );

        Map< String, List<FyDriverDTO> > params = new HashMap<>();
        params.put("drivers", Collections.singletonList( fyDriverDTO )) ;
        String bodys = JSONObject.toJSONString(params);
        String domainUrl = HyCfgUtil.getCfgItem("fanyun_daikai","url");

        String res = StrUtil.EMPTY;
        String url = domainUrl + FanyunConstant.FANYUN_DRIVER_CREATEBATCH +
                "?access_token=" + token;
        try {
            log.info("梵运批量创建司机接口请求 -> {} , {}", url, bodys);
            res = HttpUtil.post(url, bodys);
            log.info("梵运批量创建司机接口回执 <- {}", res);
            FyApiBaseResDTO result = JSONObject.parseObject(res, FyApiBaseResDTO.class);
            if (CommonConstant.SC_OK_200.intValue() == result.getCode()) {
                return res;
            }

            if (401 == result.getCode()) {
                redisUtil.del(FanyunConstant.FANYUN_TOKEN_KEY);
                throw new JeecgBootException("认证过期,请重新推送数据。");
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("FanyunApiService driverPush  Exception :{} ",e.getMessage());
        }

        return res;
    }

    /**
     * 车辆
     * @param fyVehicleDTO
     * @return
     */
    public String vehiclePush(FyVehicleDTO fyVehicleDTO){

        if(!HyCfgUtil.isUsed("fanyun_daikai")){
            throw new JeecgBootException("梵运服务暂未开启,请联系管理。");
        }
        if(fyVehicleDTO == null){
            throw new JeecgBootException("提交数据不能为空！");
        }
        String token = this.getToken();
        //判断token空
        if(StringUtils.isEmpty(token)) {
            throw new JeecgBootException("梵运服务Token为空！");
        }

        fyVehicleDTO.setOrganizationName(
                HyCfgUtil.getCfgItem2("fanyun_daikai","fy_organizationName")
        );

//        Map<String, String> headers = getHeaders();
//        Map<String, String> querys = new HashMap<>();
//        querys.put("access_token", token);
        Map< String, List<FyVehicleDTO> > params = new HashMap<>();
        params.put("vehicles", Collections.singletonList( fyVehicleDTO )) ;
        String bodys = JSONObject.toJSONString( params );
        String domainUrl = HyCfgUtil.getCfgItem("fanyun_daikai","url");

        String res = StrUtil.EMPTY;
        String url = domainUrl + FanyunConstant.FANYUN_VEHICLE_CREATEBATCH +
                "?access_token=" + token;
        try {
            log.info("梵运批量创建车辆接口请求 ->  {} , {}", url, bodys);
            res = HttpUtil.post(url, bodys);
            log.info("梵运批量创建车辆接口回执 <- {}", res);
            FyApiBaseResDTO result = JSONObject.parseObject(res, FyApiBaseResDTO.class);
            if (CommonConstant.SC_OK_200.intValue() == result.getCode()) {
                return res;
            }

            if (401 == result.getCode()) {
                redisUtil.del(FanyunConstant.FANYUN_TOKEN_KEY);
                throw new JeecgBootException("认证过期,请重新推送数据。");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("FanyunApiService vehiclePush  Exception :{} ",e.getMessage());
        }

        return res;
    }

    /**
     * 收款人
     * @param fyPayeeDTO
     * @return
     */
    public String payeePush(FyPayeeDTO fyPayeeDTO){
        if(!HyCfgUtil.isUsed("fanyun_daikai")){
            throw new JeecgBootException("梵运服务暂未开启,请联系管理。");
        }
        if(fyPayeeDTO == null){
            throw new JeecgBootException("提交数据不能为空！");
        }
        String token = this.getToken();
        //判断token空
        if(StringUtils.isEmpty(token)) {
            throw new JeecgBootException("梵运服务Token为空！");
        }

        fyPayeeDTO.setOrganizationName(
                HyCfgUtil.getCfgItem2("fanyun_daikai","fy_organizationName")
        );

        Map< String, List<FyPayeeDTO> > params = new HashMap<>();
        params.put("payees", Collections.singletonList( fyPayeeDTO )) ;
        String bodys = JSONObject.toJSONString(params);
        String domainUrl = HyCfgUtil.getCfgItem("fanyun_daikai","url");

        String res = StrUtil.EMPTY;
        String url = domainUrl + FanyunConstant.FANYUN_PAYEE_CREATEBATCH +
                "?access_token=" + token;
        try {
            log.info("梵运批量创建收款人接口请求-> {} {} ", url, bodys);
            res = HttpUtil.post(url, bodys);
            log.info("梵运批量创建收款人接口回执 <- {}", res);
            FyApiBaseResDTO result = JSONObject.parseObject(res, FyApiBaseResDTO.class);
            if (CommonConstant.SC_OK_200.intValue() == result.getCode()) {
                return res;
            }

            if (401 == result.getCode()) {
                redisUtil.del(FanyunConstant.FANYUN_TOKEN_KEY);
                throw new JeecgBootException("认证过期,请重新推送数据。");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("FanyunApiService payeePush  Exception :{} ",e.getMessage());
        }

        return res;
    }

    /**
     * 创建司机费用结算单接口
     * @param fySettlementDTO
     * @return
     */
    public String financePush(FySettlementDTO fySettlementDTO){
        if(!HyCfgUtil.isUsed("fanyun_daikai")){
            throw new JeecgBootException("梵运服务暂未开启,请联系管理。");
        }
        if(fySettlementDTO == null){
            throw new JeecgBootException("提交数据不能为空！");
        }
        String token = this.getToken();
        //判断token空
        if(StringUtils.isEmpty(token)) {
            throw new JeecgBootException("梵运服务Token为空！");
        }

        fySettlementDTO.setOrganizationName(
                HyCfgUtil.getCfgItem2("fanyun_daikai","fy_organizationName")
        );

        Map<String, String> headers = getHeaders();
        Map<String, String> querys = new HashMap<>();
        querys.put("access_token", token);

        String bodys = JSONObject.toJSONString(fySettlementDTO);
        String domainUrl = HyCfgUtil.getCfgItem("fanyun_daikai","url");

        String res = StrUtil.EMPTY;
        String url = domainUrl + FanyunConstant.FANYUN_FEE_SAVE_SETTLEMENT + "?access_token=" + token;
        try {
            log.info("梵运创建司机费用结算单接口请求-> {} {} ", url, bodys);
            res = HttpUtil.post(url, bodys);
            log.info("梵运创建司机费用结算单接口回执 <- {}", res);
            FyApiBaseResDTO result = JSONObject.parseObject(res, FyApiBaseResDTO.class);
            if (CommonConstant.SC_OK_200.intValue() == result.getCode()) {
                return res;
            }

            if (401 == result.getCode()) {
                redisUtil.del(FanyunConstant.FANYUN_TOKEN_KEY);
                throw new JeecgBootException("认证过期,请重新推送数据。");
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("FanyunApiService financePush  Exception :{} ", e.getMessage());
        }

        return res;
    }


    /**
     * 创建司机费用结算单接口(撮合)
     * @param fySettlementDTO
     * @return
     */
    public String financePushMatchUp(FySettlementDTO fySettlementDTO){
        if(!HyCfgUtil.isUsed("fanyun_daikai")){
            throw new JeecgBootException("梵运服务暂未开启,请联系管理。");
        }
        if(fySettlementDTO == null){
            throw new JeecgBootException("提交数据不能为空！");
        }
        String token = this.getToken();
        //判断token空
        if(StringUtils.isEmpty(token)) {
            throw new JeecgBootException("梵运服务Token为空！");
        }

        fySettlementDTO.setOrganizationName(
                HyCfgUtil.getCfgItem2("fanyun_daikai","fy_organizationName")
        );

        String bodys = JSONObject.toJSONString(fySettlementDTO);
        String domainUrl = HyCfgUtil.getCfgItem("fanyun_daikai","url");

        String res = StrUtil.EMPTY;
        String url = domainUrl + FanyunConstant.FANYUN_FEE_SAVE_SETTLEMENT + "?access_token=" + token;
        try {
            log.info("梵运创建司机费用结算单（撮合）接口请求-> {} {} ", url, bodys);
            res = HttpUtil.post(url, bodys);
            log.info("梵运创建司机费用结算单（撮合）接口回执 <- {}", res);
            FyApiBaseResDTO result = JSONObject.parseObject(res, FyApiBaseResDTO.class);
            if (CommonConstant.SC_OK_200.intValue() == result.getCode()) {
                return res;
            }

            if (401 == result.getCode()) {
                redisUtil.del(FanyunConstant.FANYUN_TOKEN_KEY);
                throw new JeecgBootException("认证过期,请重新推送数据。");
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("FanyunApiService financePush  Exception :{} ", e.getMessage());
        }

        return res;
    }

    /**
     * 全部核销（不支持多笔核销）
     * @param fySettlement
     * @return
     */
    public String writeoffPush(FySettlement fySettlement){
        if(!HyCfgUtil.isUsed("fanyun_daikai")){
            throw new JeecgBootException("梵运服务暂未开启,请联系管理。");
        }
        if(fySettlement == null){
            throw new JeecgBootException("提交数据不能为空！");
        }
        String token = this.getToken();
        //判断token空
        if(StringUtils.isEmpty(token)) {
            throw new JeecgBootException("梵运服务Token为空！");
        }

        String bodys = JSONObject.toJSONString( fySettlement );
        String domainUrl = HyCfgUtil.getCfgItem("fanyun_daikai","url");

        String res = StrUtil.EMPTY;
        String url = domainUrl + FanyunConstant.FANYUN_WRITEOFF + "?access_token=" + token;
        try {
            log.info("全部核销（不支持多笔核销）接口请求-> {} {} ", url, bodys);
            res = HttpUtil.post(url, bodys);
            log.info("全部核销（不支持多笔核销）接口回执 <- {}", res);
            FyApiBaseResDTO result = JSONObject.parseObject(res, FyApiBaseResDTO.class);
            if (CommonConstant.SC_OK_200.intValue() == result.getCode()) {
                return res;
            }

            if (401 == result.getCode()) {
                redisUtil.del(FanyunConstant.FANYUN_TOKEN_KEY);
                throw new JeecgBootException("认证过期,请重新推送数据。");
            }
        } catch (Exception e) {
            log.error("FanyunApiService writeoffPush  Exception :{} ",e.getMessage());
        }

        return res;
    }


    /**
     * 分笔核销司机费用结算单
     * @param fySettlement
     * @return
     */
    public String fySettlementPush(FySettlement fySettlement){
        if(!HyCfgUtil.isUsed("fanyun_daikai")){
            throw new JeecgBootException("梵运服务暂未开启,请联系管理。");
        }
        if(fySettlement == null){
            throw new JeecgBootException("提交数据不能为空！");
        }
        String token = this.getToken();
        //判断token空
        if(StringUtils.isEmpty(token)) {
            throw new JeecgBootException("梵运服务Token为空！");
        }

        String bodys = JSONObject.toJSONString( fySettlement );
        String domainUrl = HyCfgUtil.getCfgItem("fanyun_daikai","url");

        String res = StrUtil.EMPTY;
        String url = domainUrl + FanyunConstant.FANYUN_DRIVERFEE_WRITEOFF +
                "?access_token=" + token;
        try {
            log.info("梵运分笔核销司机费用结算单接口请求-> {} {} ", url, bodys);
            res = HttpUtil.post(url, bodys);
            log.info("梵运分笔核销司机费用结算单接口回执 <- {}", res);
            FyApiBaseResDTO result = JSONObject.parseObject(res, FyApiBaseResDTO.class);
            if (CommonConstant.SC_OK_200.intValue() == result.getCode()) {
                return res;
            }

            if (401 == result.getCode()) {
                redisUtil.del(FanyunConstant.FANYUN_TOKEN_KEY);
                throw new JeecgBootException("认证过期,请重新推送数据。");
            }
        } catch (Exception e) {
            log.error("FanyunApiService fySettlementPush  Exception :{} ",e.getMessage());
        }

        return res;
    }


    /**
     * 分笔核销司机费用结算单（撮合）
     * @param fySettlement
     * @return
     */
    public String fySettlementPushMatchUp(FySettlement fySettlement){

        if(fySettlement == null){
            throw new JeecgBootException("提交数据不能为空！");
        }

        String token = this.getToken();
        //判断token空
        if(StringUtils.isEmpty(token)) {
            throw new JeecgBootException("梵运服务Token为空！");
        }

        String bodys = JSONObject.toJSONString( fySettlement );
        String domainUrl = HyCfgUtil.getCfgItem("fanyun_daikai","url");

        String res = StrUtil.EMPTY;
        String url = domainUrl + FanyunConstant.FANYUN_DRIVERFEE_WRITEOFF_MATCHUP + "?access_token=" + token;
        try {
            log.info("梵运分笔核销司机费用结算单（撮合）接口请求-> {} {} ", url, bodys);
            res = HttpUtil.post(url, bodys);
            log.info("梵运分笔核销司机费用结算单（撮合）接口回执 <- {}", res);
            FyApiBaseResDTO result = JSONObject.parseObject(res, FyApiBaseResDTO.class);
            if (CommonConstant.SC_OK_200.intValue() == result.getCode()) {
                return res;
            }

            if (401 == result.getCode()) {
                redisUtil.del(FanyunConstant.FANYUN_TOKEN_KEY);
                throw new JeecgBootException("认证过期,请重新推送数据。");
            }
        } catch (Exception e) {
            log.error("FanyunApiService fySettlementPush  Exception :{} ",e.getMessage());
        }

        return res;
    }

    /**
     * 创建承运人合同接口
     * @param carrierContractDTO
     * @return
     */
    public String contractPush(CarrierContractDTO carrierContractDTO){
        if(!HyCfgUtil.isUsed("fanyun_daikai")){
            throw new JeecgBootException("梵运服务暂未开启,请联系管理。");
        }
        if(carrierContractDTO == null){
            throw new JeecgBootException("提交数据不能为空！");
        }
        String token = this.getToken();
        //判断token空
        if(StringUtils.isEmpty(token)) {
            throw new JeecgBootException("梵运服务Token为空！");
        }

        carrierContractDTO.setOrganizationName(
                HyCfgUtil.getCfgItem("fanyun_daikai","fy_organizationName")
        );

        String bodys = JSONObject.toJSONString( carrierContractDTO );
        String domainUrl = HyCfgUtil.getCfgItem("fanyun_daikai","url");

        String res = StrUtil.EMPTY;
        String url = domainUrl + FanyunConstant.FANYUN_CONTRACT_DRIVER_CREATE +
                "?access_token=" + token;
        try {
            log.info("梵运创建承运人合同接口请求-> {} {} ", url, bodys);
            res = HttpUtil.post(url, bodys);
            log.info("梵运创建承运人合同接口回执 <- {}", res);
            FyApiBaseResDTO result = JSONObject.parseObject(res, FyApiBaseResDTO.class);
            if (CommonConstant.SC_OK_200.intValue() == result.getCode()) {
                return res;
            }

            if (401 == result.getCode()) {
                redisUtil.del(FanyunConstant.FANYUN_TOKEN_KEY);
                throw new JeecgBootException("认证过期,请重新推送数据。");
            }
        } catch (Exception e) {
            log.info("FanyunApiService contractPush  Exception :{} ",e.getMessage());
        }

        return res;
    }

    /**
     * 创建撮合单票承运人合同接口
     * @param cuoheContractDTO
     * @return
     */
    public String cuoheContractPush(CuoheContractDTO cuoheContractDTO){
        if(!HyCfgUtil.isUsed("fanyun_daikai")){
            throw new JeecgBootException("梵运服务暂未开启,请联系管理。");
        }
        if(cuoheContractDTO == null){
            throw new JeecgBootException("提交数据不能为空！");
        }
        String token = this.getToken();
        //判断token空
        if(StringUtils.isEmpty(token)) {
            throw new JeecgBootException("梵运服务Token为空！");
        }

        String bodys = JSONObject.toJSONString( cuoheContractDTO );
        String domainUrl = HyCfgUtil.getCfgItem("fanyun_daikai","url");

        String res = StrUtil.EMPTY;
        String url = domainUrl + FanyunConstant.FANYUN_CONTRACT_MATCHUP_DRIVER_CREATE +
                "?access_token=" + token;
        try {
            log.info("梵运创建撮合单票承运人合同接口请求-> {} {} ", url, bodys);
            res = HttpUtil.post(url, bodys);
            log.info("梵运创建撮合单票承运人合同接口回执 <- {}", res);
            FyApiBaseResDTO result = JSONObject.parseObject(res, FyApiBaseResDTO.class);
            if (CommonConstant.SC_OK_200.intValue() == result.getCode()) {
                return res;
            }

            if (401 == result.getCode()) {
                redisUtil.del(FanyunConstant.FANYUN_TOKEN_KEY);
                throw new JeecgBootException("认证过期,请重新推送数据。");
            }

        } catch (Exception e) {
            log.error("FanyunApiService cuoheContractPush  Exception :{} ",e.getMessage());
        }

        return res;
    }

    /**
     * 上报运单轨迹接口
     * @param fyGpsDTO
     * @return
     */
    public String gpsPush(FyGpsDTO fyGpsDTO){
        if(!HyCfgUtil.isUsed("fanyun_daikai")){
            throw new JeecgBootException("梵运服务暂未开启,请联系管理。");
        }
        if(fyGpsDTO == null){
            throw new JeecgBootException("提交数据不能为空！");
        }
        String token = this.getToken();
        //判断token空
        if(StringUtils.isEmpty(token)) {
            throw new JeecgBootException("梵运服务Token为空！");
        }

        String bodys = JSONObject.toJSONString( fyGpsDTO );
        String domainUrl = HyCfgUtil.getCfgItem("fanyun_daikai","url");

        String res = StrUtil.EMPTY;
        String url = domainUrl + FanyunConstant.FANYUN_GPS_PUSH + "?access_token=" + token;
        try {
            log.info("梵运上报运单轨迹接口接口请求-> {} {} ", url, bodys);
            res = HttpUtil.post(url, bodys);
            log.info("梵运上报运单轨迹接口接口回执 <- {}", res);
            FyApiBaseResDTO result = JSONObject.parseObject(res, FyApiBaseResDTO.class);
            if (CommonConstant.SC_OK_200.intValue() == result.getCode()) {
                return res;
            }

            if (401 == result.getCode()) {
                redisUtil.del(FanyunConstant.FANYUN_TOKEN_KEY);
                throw new JeecgBootException("认证过期,请重新推送数据。");
            }
        } catch (Exception e) {
            log.info("FanyunApiService gpsPush  Exception :{} ",e.getMessage());
        }

        return res;
    }

    /**
     * 取消运单
     * @param orderNumbers
     * @return
     */
    public String cancelOrder(List<String> orderNumbers){
        if(!HyCfgUtil.isUsed("fanyun_daikai")){
            throw new JeecgBootException("梵运服务暂未开启,请联系管理。");
        }
        if(orderNumbers == null){
            throw new JeecgBootException("提交数据不能为空！");
        }
        String token = this.getToken();
        //判断token空
        if(StringUtils.isEmpty(token)) {
            throw new JeecgBootException("梵运服务Token为空！");
        }

        Map<String, String> headers = getHeaders();
        Map<String, String> querys = new HashMap<>();
        querys.put("access_token", token);
        Map< String, List<String> > params = new HashMap<>();
        params.put("orderNumbers", orderNumbers) ;

        String bodys = JSONObject.toJSONString( params );
        String domainUrl = HyCfgUtil.getCfgItem("fanyun_daikai","url");
        //String path = "/order/cancel_order"  ;
        //log.info("FanyunApiService cancelOrder url :{} bodys :{}", url+ path , bodys);

        String url = domainUrl + FanyunConstant.FANYUN_ORDER_CANCEL +
                "?access_token=" + token;
        try {
            log.info("梵运撤销运单接口请求-> {} {} ", url, bodys);
            String res = HttpUtil.post(url, bodys);
            log.info("梵运撤销运单接口回执 <- {}", res);
            FyApiBaseResDTO result = JSONObject.parseObject(res, FyApiBaseResDTO.class);
            if (CommonConstant.SC_OK_200.intValue() == result.getCode()) {
                return res;
            }

            if (401 == result.getCode()) {
                redisUtil.del(FanyunConstant.FANYUN_TOKEN_KEY);
                throw new JeecgBootException("认证过期,请重新推送数据。");
            }
//            HttpResponse response = HttpUtils.doPost(url ,  path, "POST", headers, querys, bodys);
//            int stat = response.getStatusLine().getStatusCode();
//            if (stat == 200){
//                String res = EntityUtils.toString(response.getEntity(),"UTF-8");
//                log.info("FanyunApiService cancelOrder res_obj :{} ",res);
//                FyApiBaseResDTO result = JSONObject.parseObject(res , FyApiBaseResDTO.class);
//                if(401 == result.getCode() ){
//                    redisUtil.del(FanyunConstant.FANYUN_TOKEN_KEY);
//                    throw new JeecgBootException("操作失败,请稍后重试！" );
//                }
//                return res;
//            }else{
//                log.info("FanyunApiService cancelOrder  Http code: {}  | http header error msg: {} | Http body error msg: {}",
//                        stat, response.getFirstHeader("X-Ca-Error-Message"), EntityUtils.toString(response.getEntity()));
//                throw new JeecgBootException("HTTP请求失败！" + stat);
//            }
        } catch (Exception e) {
            log.info("FanyunApiService cancelOrder  Exception :{} ",e.getMessage());
            //throw new JeecgBootException("操作失败！" + e.getMessage());
        }

        return StrUtil.EMPTY;
    }

    /**
     * 签收运单
     * @param orderNumbers
     * @return
     */
    public String signOff0rder(List<String> orderNumbers){
        if(!HyCfgUtil.isUsed("fanyun_daikai")){
            throw new JeecgBootException("梵运服务暂未开启,请联系管理。");
        }
        if(orderNumbers == null){
            throw new JeecgBootException("提交数据不能为空！");
        }
        String token = this.getToken();
        //判断token空
        if(StringUtils.isEmpty(token)) {
            throw new JeecgBootException("梵运服务Token为空！");
        }

        Map< String, List<String> > params = new HashMap<>();
        params.put("orderNumbers", orderNumbers) ;

        String bodys = JSONObject.toJSONString( params );
        String domainUrl = HyCfgUtil.getCfgItem("fanyun_daikai","url");

        String res = StrUtil.EMPTY;
        String url = domainUrl + FanyunConstant.FANYUN_ORDER_SIGNOFF + "?access_token=" + token;
        try {
            log.info("梵运签收运单请求-> {} {} ", url, bodys);
            res = HttpUtil.post(url, bodys);
            log.info("梵运签收运单回执 <- {}", res);
            FyApiBaseResDTO result = JSONObject.parseObject(res, FyApiBaseResDTO.class);
            if (CommonConstant.SC_OK_200.intValue() == result.getCode()) {
                return res;
            }

            if (401 == result.getCode()) {
                redisUtil.del(FanyunConstant.FANYUN_TOKEN_KEY);
                throw new JeecgBootException("认证过期,请重新推送数据。");
            }

        } catch (Exception e) {
            log.info("FanyunApiService signOff0rder  Exception :{} ",e.getMessage());
        }

        return res;
    }

    /**
     * 创建撮合运单接口
     * @param fyOrderDTO
     * @return
     */
    public String createOrder(FyOrderDTO fyOrderDTO){
        if(!HyCfgUtil.isUsed("fanyun_daikai")){
            throw new JeecgBootException("梵运服务暂未开启,请联系管理。");
        }
        if(fyOrderDTO == null){
            throw new JeecgBootException("提交数据不能为空！");
        }
        String token = this.getToken();
        //判断token空
        if(StringUtils.isEmpty(token)) {
            throw new JeecgBootException("梵运服务Token为空！");
        }

        OrdersDTO ordersDTO = new OrdersDTO();
        ordersDTO.setOrderMatchUpList(Collections.singletonList( fyOrderDTO) );
        ordersDTO.setOrganizationName(
                HyCfgUtil.getCfgItem("fanyun_daikai","fy_organizationName")
        );

        String bodys = JSONObject.toJSONString( ordersDTO );
        String domainUrl = HyCfgUtil.getCfgItem("fanyun_daikai","url");

        String res = StrUtil.EMPTY;
        String url = domainUrl + FanyunConstant.FANYUN_ORDER_CREATE_MATCHUP +
                "?access_token=" + token;
        try {
            log.info("梵运撮合开单请求-> {} {} ", url, bodys);
            res = HttpUtil.post(url, bodys);
            log.info("梵运撮合开单回执 <- {}", res);
            FyApiBaseResDTO result = JSONObject.parseObject(res, FyApiBaseResDTO.class);
            if (CommonConstant.SC_OK_200.intValue() == result.getCode()) {
                return res;
            }

            if (401 == result.getCode()) {
                redisUtil.del(FanyunConstant.FANYUN_TOKEN_KEY);
                throw new JeecgBootException("认证过期,请重新推送数据。");
            }

        } catch (Exception e) {
            log.info("FanyunApiService createOrder  Exception :{} ",e.getMessage());
        }

        return res;
    }

    /**
     * 更新运单接口
     * @param fyOrderDTO
     * @return
     */
    public String updateOrder(FyOrderDTO fyOrderDTO){
        if(!HyCfgUtil.isUsed("fanyun_daikai")){
            throw new JeecgBootException("梵运服务暂未开启,请联系管理。");
        }
        if(fyOrderDTO == null){
            throw new JeecgBootException("提交数据不能为空！");
        }
        String token = this.getToken();
        //判断token空
        if(StringUtils.isEmpty(token)) {
            throw new JeecgBootException("梵运服务Token为空！");
        }

        Map<String, String> headers = getHeaders();
        Map<String, String> querys = new HashMap<>();
        querys.put("access_token", token);

//        OrdersDTO ordersDTO = new OrdersDTO();
//        ordersDTO.setOrderMatchUpList(Collections.singletonList( fyOrderDTO) );
//        ordersDTO.setOrganizationName(
//                HyCfgUtil.getCfgItem("fanyun_daikai","fy_organizationName")
//        );

        String bodys = JSONObject.toJSONString( fyOrderDTO );
        String domainUrl = HyCfgUtil.getCfgItem("fanyun_daikai","url");
//        String path = "/order/update_order"  ;
//        log.info("FanyunApiService updateOrder url :{} bodys :{}", url+ path , bodys);

        String url = domainUrl + FanyunConstant.FANYUN_ORDER_UPDATE +
                "?access_token=" + token;
        try {
            log.info("梵运更新运单请求-> {} {} ", url, bodys);
            String res = HttpUtil.post(url, bodys);
            log.info("梵运更新运单回执 <- {}", res);
            FyApiBaseResDTO result = JSONObject.parseObject(res, FyApiBaseResDTO.class);
            if (CommonConstant.SC_OK_200.intValue() == result.getCode()) {
                return res;
            }

            if (401 == result.getCode()) {
                redisUtil.del(FanyunConstant.FANYUN_TOKEN_KEY);
                throw new JeecgBootException("认证过期,请重新推送数据。");
            }
//            HttpResponse response = HttpUtils.doPost(url ,  path, "POST", headers, querys, bodys);
//            int stat = response.getStatusLine().getStatusCode();
//            if (stat == 200){
//                String res = EntityUtils.toString(response.getEntity(),"UTF-8");
//                log.info("FanyunApiService updateOrder res_obj :{} ",res);
//                FyApiBaseResDTO result = JSONObject.parseObject(res , FyApiBaseResDTO.class);
//                if(401 == result.getCode() ){
//                    redisUtil.del(FanyunConstant.FANYUN_TOKEN_KEY);
//                    throw new JeecgBootException("操作失败,请稍后重试！" );
//                }
//                return res;
//            }else{
//                log.info("FanyunApiService updateOrder  Http code: {}  | http header error msg: {} | Http body error msg: {}",
//                        stat, response.getFirstHeader("X-Ca-Error-Message"), EntityUtils.toString(response.getEntity()));
//                throw new JeecgBootException("HTTP请求失败！" + stat);
//            }
        } catch (Exception e) {
            log.info("FanyunApiService updateOrder  Exception :{} ",e.getMessage());
            //throw new JeecgBootException("操作失败！" + e.getMessage());
        }

        return StrUtil.EMPTY;
    }







}
